package com.qd.core.service.user;

import com.qd.common.sys.domain.entity.login.LoginUserDTO;
import com.qd.common.sys.domain.entity.role.RoleDTO;
import com.qd.common.sys.domain.login.LoginUser;
import com.qd.common.sys.enums.RemoteEnum;
import com.qd.core.service.SysPermissionService;
import com.qd.system.service.login.LoginUserService;
import com.qd.system.service.person.PersonRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户验证处理
 * 按照用户名登录
 *
 * @author sjk
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AccountUserDetailsServiceImpl implements CustomUserDetailService {

    private final LoginUserService loginUserService;
    private final SysPermissionService permissionService;
    private final PersonRoleService personRoleService;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final LoginUserDTO user = loginUserService.selectUserByUserNameDto(username);
        if (null == user) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        return createLoginUser(user);
    }

    private UserDetails createLoginUser(LoginUserDTO user) {
        final List<RoleDTO> roleList = personRoleService.getRoleByPersonId(user.getPersonId());
        if (!roleList.isEmpty()) {
            user.setRoles(roleList);
        }
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }

    @Override
    public Boolean remote(String platform) {
        return platform.equals(RemoteEnum.WEB.getMsg());
    }
}
